<template lang="pug">
    div(class="forum-post-detail")
        div(class="forum-post-detail_main")
            el-row
                el-col(:span="3")
                    el-image(:lazy="true", :src="item.avatar", class="forum-post-detail__avatar", @click.stop="userZoneVisible=true")
                el-col(:span="16")
                    div(class="forum-post-detail__uname") 
                      span(@click.stop="userZoneVisible=true") {{item.wxUName}}
                    div(class="forum-post-detail__ctime")
                        small {{item.postCreateAt | format('YYYY-MM-DD HH:mm')}}
                el-col(:span="5")
                  follow-button(:target-wx-uid="item.wxUId",:is-following.sync="item.followed")
            div(class="forum-post-detail__item__content")
                p
                  span(v-if="item.postTitle") 【{{item.postTitle}}】
                  span(v-html="item.postContent")
                div(style="margin: -10px;")
                    cube(:images="getImages(item.images)")
            div(class="forum-post-detail__item__social")
              el-row
                el-col(:offset="1")
                  span &nbsp;{{item.accessCount}}阅读
            lazyload-mark(:data="item",@show="handleAccess")
        
        div(class="forum-post-detail_comments")
          div(class="comment-toolbar")
            el-row
              el-col(:span="4", :offset="1")
                svg(class="icon forum-post-detail__item__social_icon", aria-hidden="true",@click="favorite(item)")
                    use(:xlink:href="item.isFavorite ?'#icon-shoucang-' : '#icon-shoucang'")
              el-col(:span="8")
                span(class="comment-label") 评论&nbsp;{{item.commentCount}}
              el-col(:span="10", style="text-align:right")
                span(@click="like(item)", :class="{active: item.isLike }") 赞&nbsp; {{item.likeCount}}

          comment(ref="comment",:post-id="item.postId", 
            @empty-action-click="showCommentForm",
            @comment-success="commentSuccess")
        active-panel(:visible="userZoneVisible", @history-back="userZoneVisible=false")
          zone(:wx-uid="item.wxUId")

</template>

<script>
import axios from "@/plugins/axios";
import BaseVue from "@/mixins/BaseVue";
import cube from "./cube";
import comment from "@/pages/components/comment/index.vue";
import store from "@/plugins/store";
import LazyloadMark from "@/pages/components/lazyload-mark";
import accessStore from "@/store/AccessStore";
import FollowButton from "@/pages/components/follow-button";
import util from "@/libs/util";

export default {
  name: "post-detail",
  mixins: [BaseVue],
  components: {
    cube: cube,
    comment: comment,
    "lazyload-mark": LazyloadMark,
    "follow-button": FollowButton
  },
  data() {
    return {
      item: {},
      query: false,
      base_url: process.env.NODE_ENV !== "development" ? "/" : "/api/",
      /**用戶中心是否可見 */
      userZoneVisible: false,

      has_add_access_record: false,

      WxShare: null
    };
  },

  props: {
    postId: { type: String, default: null }
  },
  watch: {
    postId(val) {
      if (val) this.getPost(postId);
    }
  },
  methods: {
    getPost(id) {
      const options = {
        url: "forum/home/post",
        method: "post",
        data: { id: id }
      };
      this.query = true;
      axios(options)
        .then(item => {
          this.getPostSuccess(item);
          this.setShare();
        })
        .catch(e => (this.query = false));
    },
    getPostSuccess(item) {
      this.item = item;
      this.query = false;
    },
    like(item) {
      const options = {
        url: "forum/home/like",
        method: "post",
        data: { postId: item.postId }
      };
      // 在请求前就需要把item.isLike状态进行改变，从而实现用户看到界面有了点赞的改变。
      // 如果下文中请求服务器失败，则要改回状态
      this.changeLikeState(item);
      axios(options)
        .then(() => this.likeSuccess())
        .catch(() => this.changeLikeState(item));
    },
    changeLikeState(item) {
      item.isLike = !item.isLike;
      item.likeCount = item.isLike ? item.likeCount + 1 : item.likeCount - 1;
    },
    likeSuccess() {},
    favorite(item) {
      const options = {
        url: "forum/favorite/postFavorite",
        method: "post",
        data: { postId: item.postId }
      };
      // 在请求前就需要把item.isFavorite状态进行改变，从而实现用户看到界面有了点赞的改变。
      // 如果下文中请求服务器失败，则要改回状态
      this.changeFavoriteState(item);
      axios(options)
        .then(() => {})
        .catch(() => this.changeFavoriteState(item));
    },
    changeFavoriteState(item) {
      item.isFavorite = !item.isFavorite;
    },
    getImages(images) {
      if (!images) return [];
      const vm = this;
      return images.map(image => {
        return { url: vm.base_url + image };
      });
    },
    /**
     * 显示评论表单
     */
    showCommentForm() {
      this.$refs.comment.showForm();
    },
    handleAccess(post) {
      this.$nextTick(() => {
        accessStore.commit("add_record", this.item.postId);
      });
    },
    commentSuccess(comment) {},
    beforedestroy() {
      // this.restoreShare();
    },
    setShare() {
      if (this.item.postTitle) util.title(this.item.postTitle);
      axios({
        url: "weixin/web",
        method: "post",
        data: { url: location.href }
      }).then(data => {
        let pic =
          "https://img.yzcdn.cn/upload_files/2018/12/04/Fs2MKthTfft2XLKQbxIP98sTO5VH.jpg";
        if (this.item && this.item.images && this.item.images.length) {
          var url = this.getImages([this.item.images[0]])[0].url;
          if (url) {
            if (url.indexOf("http") === -1 && url.indexOf("https") === -1) {
              pic = location.origin + url;
            } else {
              pic = url;
            }
          }
        }
        let content = "健蓓论坛";
        const postContent = this.item.postContent;
        if (postContent) {
          content = postContent.replace(/<[^>]+>/g, "").substring(0, 100);
        }
        let title = "来自" + this.item.wxUName + "的帖子-" + "健蓓论坛";
        if (this.item.postTitle) title = this.item.postTitle;
        data.debug = false;
        data.jsApiList = ["updateAppMessageShareData"];
        wx.config(data);

        const link = `${location.origin}${location.pathname}#/home/detail/${
          this.item.postId
        }?a=1`;

        wx.ready(() => {
          wx.updateAppMessageShareData({
            title: title,
            desc: content,
            imgUrl: pic,
            link: link
          });
        });
      });
    }
  },
  mounted() {
    const postId = this.$route.params.id;
    if (postId) this.getPost(postId);
    if (this.postId) this.getPost(this.postId);
    this.item.postId = postId || this.postId;
  }
};
</script>

<style lang="less">
@import "../../common/common.less";

.forum-post-detail {
  background-color: @page_background;
  height: 100vh;

  @main-padding-left: 5px;
  @main-padding-bottom: 10px;
  &_main {
    background-color: white;
    padding: @main-padding-bottom @main-padding-left;
  }

  &__avatar {
    @width: 40px;
    width: @width;
    height: @width;
    border-radius: @width;
  }
  &__item {
    padding: 15px 2px 0;
    margin-bottom: 10px;

    &__content {
      padding-bottom: 18px;
    }

    &__social {
      border-top: 1px solid #e9e9e9;
      height: 32px;
      line-height: 32px;
      margin-left: -@main-padding-left;
      margin-right: -@main-padding-left;
      margin-bottom: -@main-padding-bottom;

      a {
        text-decoration: none;
        color: inherit;
      }

      &_icon {
        @edage: 14px;
        width: @edage;
        height: @edage;
      }
    }
  }

  &__uname {
    color: #eb7350;
    font-weight: bold;
  }

  &__ctime {
    color: grey;
  }

  &__avatar {
    @edge: 2.5em;
    width: @edge;
    height: @edge;
  }

  &_comments {
    margin-top: 8px;

    .comment-toolbar {
      @comment-toolbr-height: 32px;
      height: @comment-toolbr-height;
      line-height: @comment-toolbr-height;
      background-color: white;
      border-bottom: #e9e9e9 1px solid;

      @color: #f76665;
      .comment-label {
        color: @color;
        border-bottom: 1.5px solid @color;
        height: @comment-toolbr-height;
        display: inline-block;
      }
      .active {
        color: @color;
      }
    }
  }
}
</style>
